import { useToggle } from "ahooks";
import clsx from "clsx";
import { useEffect, useRef, useState } from "react";
import { useForm } from "../../framework/common/context/metadata-context";
import watermark, { removeWatermark } from "../../framework/common/utils/watermark";
import DataContent from "./DataContent";
import { v4 as uuid } from "uuid";
import eventBus, { useSubscribe } from "../../framework/common/eventBus";
import get from "lodash/get";
import { triggerGroupRowRule, triggerSqlAPIValueCaculate } from "../../framework/common/rule/setRuleResult";
import { fieldFilter } from "../../framework/common/utils/filter";
import jQuery from "jquery";
import useOperationConnect from "../../framework/common/lifecycle/useOperationConnect";
//分组标题
export default function ({ groupCode, isSubTable, title, groupTitleClsName, groupRef, contentRef, group, data = [] }) {
  const form = useForm();
  const { isDisplay, mode } = form.root;
  const [isFullScreen, { toggle }] = useToggle(false);
  const [visible, setVisible] = useState(true);

  const titleRef = useRef();
  let isPrint = form.mode === "Print";

  useEffect(() => {
    if (isSubTable) {
      //子表有无数据
      let filterFields = group.fields?.filter(fieldFilter).filter((f) => f.isHidden !== true);

      if (filterFields?.length === 0) {
        setVisible(false);
      } else {
        setVisible(true);
      }
    } else {
      //主表有无数据
      let isAllRowEmpty = true;
      group.rows?.forEach((row, index) => {
        let isEmptyRow = row.cols.every((col) => col.isEmpty === true || col.isHidden === true);
        if (isEmptyRow === false) {
          isAllRowEmpty = false;
        }
      });
      setVisible(!isAllRowEmpty);
    }
  });

  const operationConnector = useOperationConnect(
    () => titleRef.current?.getBoundingClientRect(),
    () => groupRef.current?.getBoundingClientRect(),
    {
      group: group,
      type: "group",
    }
  );

  //子表全屏和导出Excel按钮
  let buttons = null;
  const virtualGroup = useRef();
  let [virtualTable, setVirtualTable] = useState();
  if (visible === false) {
    return null;
  }
  if (isSubTable) {
    //全屏
    function handleFullScreen() {
      toggle();
      let mainContent = document.querySelector(".main-content");
      if (isFullScreen === false) {
        //全屏模式
        mainContent.classList.add("full-screen-mode");
        groupRef.current.classList.add("full-screen-mode");
        contentRef.current.classList.add("full-screen-mode");
        document.body.classList.add("overflow-hidden");
        document.querySelector("#header").classList.add("full-screen-mode"); //子表最大化时会挡住头部里面的tip
        //左右小老虎
        document.querySelector(".textLanternRight").classList.add("hidden");
        document.querySelector(".textLanternLeft").classList.add("hidden");
        watermark(form.data.watermark.content, groupRef.current);
      } else {
        //退出全屏模式
        mainContent.classList.remove("full-screen-mode");
        groupRef.current.classList.remove("full-screen-mode");
        contentRef.current.classList.remove("full-screen-mode");
        document.body.classList.remove("overflow-hidden");
        document.querySelector("#header").classList.remove("full-screen-mode");
        document.querySelector(".textLanternRight").classList.remove("hidden");
        document.querySelector(".textLanternLeft").classList.remove("hidden");
        removeWatermark(groupRef.current);
      }
      eventBus.publish(`group.update.${group.code}`);
    }

    //导出excel
    function handleExportExcel() {
      let data = form.data.form.form_data?.children?.[groupCode]; //当前子表数据
      //data：tbody数据 group：完整的group数据
      //实际的导出动作，通过加载虚拟dom来完成，在DataContent组件内实现
      setVirtualTable(<DataContent key={uuid()} isVirtualTable={true} ref={virtualGroup} data={data} group={group}></DataContent>); //生成虚拟dom，用于导出excel遍历dom拿到数据
    }

    //是否显示导出Excel
    //$data.loop_table_export_excel && !datalist_has_rights($data) && $data.rows && $data.rows.length && !$data.table_group_title}}\
    let isExport = !!(group.loop_table_export_excel && group.rows && group.rows.length && !group.table_group_title); //开启了导出excel && 当前分组有数据 && 没有开启多行头
    if (!isDisplay) {
      //可编辑模式
      group.columns.find(function (item) {
        if (item.is_editable) {
          //只要有列存在可编辑
          isExport = false; //就禁止导出Excel
          return true;
        }
      });
    }

    function handleAddRow() {
      //这里取默认值的情况
      let addedRow = { __cid__: uuid() };
      group.fields.forEach((f) => {
        if (f.props?.source_type === "fixd_value") {
          //如果配置了默认值，就用默认值
          if (f.props?.default_value !== undefined) {
            addedRow[f.code] = f.props?.default_value;
          } else if (f.props?.configs && Array.isArray(f.props?.configs)) {
            let defaultValueArray = f.props.configs.find((v) => v[0] == 1) || [];

            if (f.type === "checkbox_group") {
              if (defaultValueArray[1] !== undefined) {
                addedRow[f.code] = defaultValueArray[1];
              }
            } else {
              if (defaultValueArray[2] !== undefined) {
                addedRow[f.code] = defaultValueArray[2];
              }
            }
          }
          //show_zero规则：没有值设置为0
          if (f.props?.handle_null_value === "show_zero" && (f.props?.default_value === "" || f.props?.default_value === null)) {
            addedRow[f.code] = f.props?.default_value; //子表新增行，如果字段没有默认值，且配置的为空显示为0，则默认值以业务对象定义的默认值为准
          }
        } else {
          //其他类型的source type需要从data_range取
          // "checkbox_group"
          let value = get(form.data, `form.data_range.children.${group.code}.${f.code}`, null);
          if ((f.type === "checkbox_group" || f.type === "radio" || f.type === "dropdown") && Array.isArray(value)) {
            let defaultValueArray = value.find((v) => v[0] == 1) || [];
            //checkbox从索引1里面取
            if (f.type === "checkbox_group") {
              if (defaultValueArray[1] !== undefined) {
                value = defaultValueArray[1];
              }
            } else {
              if (defaultValueArray[2] !== undefined) {
                value = defaultValueArray[2];
              }
            }
          }

          addedRow[f.code] = value;
        }
      });
      data.push(addedRow);
      triggerGroupRowRule(group, data.length - 1, form?.data?.form?.data_define);
      eventBus.publish("group.update." + group.code);
      triggerSqlAPIValueCaculate(form, group, data.length - 1);

      window.jQuery = jQuery;
      setTimeout(() => {
        jQuery("#" + group.code + "Container").scrollTop(jQuery("#" + group.code + "Container").prop("scrollHeight"));
      }, 0);
    }

    //如果字段全部不能编辑，就不现实添加
    let anyEditable = group.columns.find((c) => c?.is_editable === true);
    buttons = (
      <span className="top-0 right-0 mr-3 font-normal select-none title-tool v-center text-color-333">
        {isPrint !== true &&isExport && (
          <span className="mr-6 text-sm font-normal cursor-pointer text-color-333 font-yahei" onClick={handleExportExcel}>
            <i className="mr-1 text-sm iconfont icon-excel text-primary"></i>
            导出Excel
          </span>
        )}
        {isPrint !== true && (
          <span className="text-sm font-normal cursor-pointer text-color-333 font-yahei" onClick={handleFullScreen}>
            <i className={clsx("iconfont text-sm text-primary mr-1", isFullScreen ? "icon-tuichuquanping" : "icon-quanping")}></i>
            {isFullScreen ? "退出全屏" : "全屏"}
          </span>
        )}
        {group.isAdd && anyEditable && !isDisplay && (
          <span className="ml-6 text-sm font-normal cursor-pointer text-color-333 font-yahei" onClick={handleAddRow}>
            <i className={clsx("iconfont text-sm text-primary mr-1 icon-tianjia")}></i>
            添加
          </span>
        )}
      </span>
    );
  }

  // function handleMouseEnter(){
  //   let rect=groupRef.current.getBoundingClientRect();
  //   eventBus.publish("drawLayer",rect)
  // }

  // function handleMouseLeave(event){
  //   if (!isMouseInDomRect(event,titleRef.current.getBoundingClientRect())) {
  //     eventBus.publish("clearLayer")
  //   }
  // }
  return (
    <>
      {group.titleSetting !== true ? (
        <div ref={titleRef} {...operationConnector} className={clsx("group-title leading-24px relative min-w-0 px-3 pt-3px pb-3px", groupTitleClsName, form.showBorder ? "bg-gray-e9" : "bg-gray-60")}>
          {title}
          {buttons}
        </div>
      ) : (
        buttons && <div className={clsx("group-title  h-[30px] relative min-w-0 px-3 pt-3px pb-3px", groupTitleClsName, form.showBorder ? "bg-gray-e9" : "bg-gray-60")}>{buttons}</div>
      )}
      {virtualTable}
    </>
  );
}
